package com.efounder.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.drawerlayout.widget.DrawerLayout;

import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.aspect.annotation.ExecutionTime;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.model.Constant;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.model.UpdateResEvent;
import com.efounder.common.floatwindow.FloatWindowService;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JResponseObject;
import com.efounder.fragment.LeftDrawerFragment;
import com.efounder.fragment.MainFragment;
import com.efounder.fragment.MenuFragment;
import com.efounder.fragment.PagerSlidingTab2Fragment;
import com.efounder.fragment.PagerSlidingTabFragment;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.model.APKUpdateManager;
import com.efounder.model.IBaseMainHome;
import com.efounder.model.LoginUtil;
import com.efounder.model.LoginUtilInterface;
import com.efounder.model.RESUpdateManager;
import com.efounder.model.RefreshMainNineGridViewEvent;
import com.efounder.model.RefreshViewEvent;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.skin.CustomSDCardLoader;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.LogOutUtil;
import com.efounder.util.LoginManager;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.PackgeFileCheckUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.widget.ESPWebView;
import com.efounder.widget.TabBarNew;
import com.pansoft.resmanager.ResFileManager;
import com.pansoft.resmanager.ResLoadManager;
import com.pansoft.start.LoginCheckManager;
import com.pansoft.xmlparse.OptionParser;
import com.tencent.bugly.crashreport.CrashReport;
import com.utilcode.util.AppUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;

import skin.support.SkinCompatManager;

import static com.efounder.chat.model.Constant.SKIN_DIR;
import static com.efounder.forwechat.BaseApp.context;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;

/**
 * 首页TabBottomActivity所要继承的基类
 * 封装了配置文件加载生成tab、bottomBar
 * Tab的activity、fragment管理
 * 侧边抽屉、悬浮窗等的开启
 * 检查更新、用户登录可在继承类里自己实现
 * <p>
 * 请不要直接使用，请在继承该类后使用
 *
 * @author wang
 */
public class BaseMainHomeActivity extends AbActivity implements IBaseMainHome,
        TabBarNew.OnCurrentTabChangedListener, MenuFragment.RefreshforDefineMenu {

    protected String TAG;

    public static final String KEY_MENU_ROOT = "menuRoot";

    /**
     * 主菜单
     */
    protected List<StubObject> mainMenuList;

    /**
     * 当前Tab页面索引
     */
    protected int currentTabIndex;
    /**
     * 放置菜单的view
     */
    protected TabBarNew tabbarView;
    private AbBottomBar mBottomBar;

    public static BaseMainHomeActivity mySelf;
    protected TabBottomActivityResultListener onTabBottomActivityResultListener;

    /**
     * 上一次点击返回按钮的时间
     */
    private long lastClickBackTime;

    private FragmentManager fragmentManager;

    /**
     * 将要显示的fragmetn
     */
    private BaseFragment willShowFragment;
    /**
     * 将要隐藏的fragment
     */
    private BaseFragment willHideFragment;
    /**
     * 缓存主菜单对应的Fragments
     */
    protected BaseFragment[] cachedFragments;

    /**
     * IM消息聊天id 和password
     */
    protected String chatUserID;
    protected String chatPassword;

    /**
     * APP以及资源文件更新管理
     */
    protected APKUpdateManager apkUpdateManager;

    /**
     * 消息推送管理（反射的方式）
     */
    protected ReflectUtils reflectPushManager;

    /**
     * 处理更新回调的handler 用处已不大，旧项目有使用
     */
    protected Handler checkUpdateHandler;

    // ----------------提供接口--------------------
    public static BaseMainHomeActivity getInstance() {
        return mySelf;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
        loadProfile();
        doBeforeSetContentView();
        setAbContentView(R.layout.tab_bottom_n);

        chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID, "");
        chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD, "");

        //资源文件不完整，不再继续往下执行代码
        if (!checkProfileIsFull()) {
            return;
        }
        //检查env中是否存在用户
        if (!checkUserValid()) {
            return;
        }
        //bugly设置登录用户id,这样我们可以知道哪个用户闪退
        CrashReport.setUserId(EnvironmentVariable.getUserName());
        //加载配置文件
//        loadProfile();
        initOtherParams();
        //生成menu菜单以及view
        generaterMenuView();
        //检查应用更新
        checkUpdateAndGnqx();
        mySelf = this;

        //初始化华为推送
        initHuaweiPush();
    }


    @Override
    public void doBeforeSetContentView() {
        //从配置文件读取字体颜色配置
        applyFontAndColorFromXmlOptions();
        //设置不可滑动返回
        getSwipeBackLayout().setEnableGesture(false);
    }

    @Override
    public void loadProfile() {
        //注册配置文件
        Registry.init(ResFileManager.PACKAGE_DIR);
    }

    /**
     * 初始化一些其他属性
     */
    protected void initOtherParams() {
        //XXX-为activity注册的默认 音频通道 。
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        // 设置默认显示的标签页
        fragmentManager = getSupportFragmentManager();
        //app升级管理
        apkUpdateManager = new APKUpdateManager();
        checkUpdateHandler = new MyHandler(this);
        //是否加载静态的webview 可能是支持某个项目使用的，暂时不用
        String isLoadStaticWebView = EnvironmentVariable.getProperty("isLoadStaticWebView");
        if ((null != isLoadStaticWebView && !isLoadStaticWebView.equals("1"))) {
            initWebView();
        }
        getTitleBar().setVisibility(View.GONE);
        //注册监听
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public boolean isAllowLeftDrawer() {
        return true;
    }

    @Override
    public BaseFragment getLeftDrawerFragment() {
        return new LeftDrawerFragment();
    }

    @Override
    public void refreshUi() {
        //清空配置文件
        Registry.clearRegistry();
        OptionParser.getInstance().release();
        mainMenuList = null;
        loadProfile();
        generaterMenuView();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initPush();
        //初始化悬浮窗服务
        initFloatWindow(false);
        if (isAllowLeftDrawer()) {
            initDrawerLayout();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentManager.popBackStack();
            return;
        }
        if (System.currentTimeMillis() - lastClickBackTime > 3000) {
            ToastUtils.showShort(R.string.mobile_lib_press_back_again_exit);
            lastClickBackTime = System.currentTimeMillis();
        } else {
            moveTaskToBack(false);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //防止被回收
        super.onSaveInstanceState(outState);
        // outState.putSerializable("databack", (Serializable) mainMenuList);
        outState.putInt("currentTabIndex", currentTabIndex);
//        Log.e("yqs", "onSaveInstanceState");


    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
//        Log.e("yqs", "onRestoreInstanceState");

//        currentTabIndex = savedInstanceState.getInt("currentTabIndex", 0);
//        if (mainMenuList == null) {
//            getMain_Menu_FromXml();
//        }
//        showFragment(currentTabIndex);
    }

    @Override
    public void onCurrentTabChanged(int index) {
        showMenuByIndex(index);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (onTabBottomActivityResultListener != null) {
                onTabBottomActivityResultListener.onTabBottomActivityResult(requestCode, resultCode, data);
            }
        } else if (resultCode == FloatWindowService.REQUEST_CODE_PERMISSON_OVERLAY) {
            //请求弹框权限
            initFloatWindow(true);
        }
    }

    @ExecutionTime("onStop的执行时间")
    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mySelf = null;
    }

    /**
     * 初始化DrawerLayout
     */
    protected void initDrawerLayout() {
        //设置允许打开左边抽屉
        getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
        //避免出现划出左侧抽屉空白问题
        if (getSupportFragmentManager().findFragmentByTag("tag_LeftDrawerFragment") == null) {
            //设置左边抽屉Fragment
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(getDrawerLayoutLeftLayoutResId(), getLeftDrawerFragment(), "tag_LeftDrawerFragment").commit();
        }
    }

    /**
     * 初始化手机的push功能 获取token(反射实现)
     */
    protected void initPush() {
        try {
            if (reflectPushManager == null) {
                reflectPushManager = ReflectUtils.reflect("com.efounder.push.PushManager").newInstance(this);
            }
            //清除小米push 角标
            reflectPushManager.method("clearPushNotification");
            //google FCM推送
            reflectPushManager.method("getFCMPushToken");
        } catch (Exception e) {
            LogUtils.e("PushManager初始化失败，可能不支持推送");
        }
    }

    /**
     * 初始化华为推送，需要oncreate中调用
     */
    protected void initHuaweiPush() {
        try {
            if (reflectPushManager == null) {
                reflectPushManager = ReflectUtils.reflect("com.efounder.push.PushManager").newInstance(this);
            }
            reflectPushManager.method("initPushTokenAndConnect");
        } catch (Exception e) {
        }
    }

    /**
     * 生成菜单相应界面
     */
    protected void generaterMenuView() {
        //加载配置文件
        if (mainMenuList == null) {
            mainMenuList = getMainMenuList();
        }
        makeMainMenu();
    }

    protected void initWebView() {
        MyStaticWebView.newInstance(BaseMainHomeActivity.this
                .getApplicationContext());
        MyStaticWebView.getWv().setJsToandroidCallBack(
                new ESPWebView.JsToandroidCallBack() {
                    @Override
                    public void html5initover() {
                    }
                });
        MyStaticWebView.getWv().setEspContext(this);
    }

    /**
     * 加载完主菜单之后调用, 生存主菜单布局
     */
    private void makeMainMenu() {
        if (mainMenuList == null) {
            Toast.makeText(this, ResStringUtil.getString(R.string.common_text_http_request_data_fail), Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }
        cachedFragments = new BaseFragment[mainMenuList.size()];
        loadBottomBar(mainMenuList);
    }

    private void loadBottomBar(List<StubObject> espMenuList) {
        tabbarView = new TabBarNew(this, espMenuList);
        if (tabbarView.getTopOutPosition() != -1) {
            this.changeNavigationHeight();
        }
        mBottomBar = this.getBottomBar();
        mBottomBar.removeAllViews();
        mBottomBar.setVisibility(View.VISIBLE);

        FrameLayout.LayoutParams tabParams = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                SizeUtils.dp2px(50));
        tabParams.gravity = Gravity.BOTTOM;
        mBottomBar.addView(tabbarView, tabParams);
        tabbarView.setOnCurrentTabChangedListener(this);

        //获取应用初始要展示的菜单index
        currentTabIndex = getDefaultDisplayIndex();
        if (getIntent().hasExtra("shareToZone")) {
            tabbarView.setCurrentTab(1);
            currentTabIndex = 1;
        }
        //根据index显示页面
        showMenuByIndex(currentTabIndex);
//        showFragment(currentTabIndex);

//        willHideFragment = willShowFragment;
//        willShowFragment = initAndCacheFragment(currentTabIndex);
//        showFragment(willShowFragment);
        // checkUpdateHandler.sendEmptyMessage(6);
    }


    /**
     * 获取应用打开时，默认显示第几个tab页面
     * 目前是从配置文件读取，可以重写这个方法返回相应的index
     *
     * @return
     */
    protected int getDefaultDisplayIndex() {
        int defaultPosition = tabbarView.getDefaultSelectedTab();
        return defaultPosition;
    }

    /**
     * 切换tab，加载fragment 或者 activity
     *
     * @param index tab index
     */
    protected void showMenuByIndex(int index) {
        StubObject menuItem = mainMenuList.get(index);
        //判断点击该菜单是否是打开fragment
        String isActivity = menuItem.getString("isActivity", "");
        if (isActivity.equals("true")) {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = null;
            try {
                List<StubObject> subMenus = Registry.getRegEntryList((String) menuItem.getID());
                StubObject stubObject = subMenus.get(0);
                String androidShow = stubObject.getString("AndroidShow", "");
                clazz = loader.loadClass(androidShow);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (clazz != null) {
                startActivity(new Intent(this, clazz));
            }
        } else {
            showFragment(index);
        }
    }

    /**
     * 显示当前index的menu的fragment
     *
     * @param index
     */
    public void showFragment(int index) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // 取缓存
        if (cachedFragments[index] != null) {
            willShowFragment = cachedFragments[index];
        } else {
            willShowFragment = initAndCacheFragment(index);
            fragmentTransaction.add(R.id.mainContent, willShowFragment);
        }
        //todo yqs 20191112 这段代码不应该使用，暂时屏蔽掉
//        getCurrentFragment().onPause();
//        // 启动目标tab的onStart()
//        if (willShowFragment.isAdded()) {
//            willShowFragment.onStart();
//        } else {
////            ft.add(R.id.mainContent, willShowFragment);
//        }

        // 显示目标tab
        showTab(fragmentTransaction, index);

    }

    public Fragment getCurrentFragment() {
        return cachedFragments[currentTabIndex];
    }


    /**
     * 创建并且缓存Fragment
     *
     * @param index 索引
     */
    private BaseFragment initAndCacheFragment(int index) {
        StubObject mainMenuItem = mainMenuList.get(index);
        AbFragmentManager ab = new AbFragmentManager(this);
        // 根据viewtype的类型得到
        BaseFragment baseFragment = ab.getFragment(mainMenuItem);
        baseFragment.setBadgeType("" + index);
        cachedFragments[index] = baseFragment; // 缓存
        baseFragment.setAlone(false);
        return baseFragment;
    }


    /**
     * 切换TAB
     *
     * @param fragmentTransaction
     * @param index               要显示的index
     */
    private void showTab(FragmentTransaction fragmentTransaction, int index) {
        willShowFragment = cachedFragments[index];
        willHideFragment = cachedFragments[currentTabIndex];
        if (willHideFragment != null && !willShowFragment.equals(willHideFragment)) {
            fragmentTransaction.hide(willHideFragment);
        }
        if (willShowFragment != null) {
            fragmentTransaction.show(willShowFragment);
        }
        fragmentTransaction.commitAllowingStateLoss();
        currentTabIndex = index;
        tabbarView.setCurrentTabColor(index);
        TabBarNew.mCurrentTabIndex = index;
        mBottomBar.onTabChanged(index);
    }


    public void jumpAndStoreStack(Fragment fragment) {
        if (fragment == null) {
            return;
        }
        FragmentTransaction trasaction = fragmentManager.beginTransaction();
        trasaction.add(R.id.mainContent, fragment, fragment.getClass().getName());
        trasaction.addToBackStack(null);
        trasaction.commit();
    }

    public void popBackStack() {
        fragmentManager.popBackStack();
    }

    /**
     * 获取主页菜单
     *
     * @return
     */
    @Override
    public List<StubObject> getMainMenuList() {
        mainMenuList = Registry.getRegEntryList(KEY_MENU_ROOT);
        List<StubObject> defaultMenus = Registry.getRegEntryList("DefaultOpenMenu");
        //菜单国际化处理
        ResLoadManager.loadMultiLanguageMenu();
        if (mainMenuList == null && defaultMenus != null) {
            mainMenuList = defaultMenus;
        }
//        处理功能权限过滤菜单
        MenuGnqxUtil.handleGNQX(mainMenuList);
        return mainMenuList;
    }

    private void initFloatWindow(boolean isOnactivityresult) {
        if (FloatWindowService.checkOverLayPermission(this, isOnactivityresult)) {
            FloatWindowService.startFloatService(this);
        }
    }


    /**
     * 初始化rn和状态栏字体颜色
     * * 这个代码项目中其实已经用不到了，老项目使用的，所以暂时保留
     */
    @Deprecated
    protected void applyFontAndColorFromXmlOptions() {
        //*************************初始化RN颜色**********start***************
        Map<String, String> interest = OptionParser.getInstance()
                .getElementById("RNTitleBackGround");
        if (null != interest) {
            String RNTitleBackGround = interest.get("value");
            if (RNTitleBackGround != null) {
                EnvironmentVariable.setProperty("navcolor", RNTitleBackGround);
            }
        }

        //判断状态栏字体是否需要设置成dark
        Map<String, String> statusDark = OptionParser.getInstance()
                .getElementById("statusDark");
        if (null != statusDark) {
            String statusDarkValue = statusDark.get("value");
            SharedPreferences mSharedPreferences = getSharedPreferences("mSharedPreferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = mSharedPreferences.edit();
            if (statusDarkValue != null) {
                edit.putString("statusDarkValue", statusDarkValue);
                edit.commit();
            }
        }
    }

    /**
     * 检查资源文件是否完整
     *
     * @return
     */
    protected boolean checkProfileIsFull() {
        boolean isFull = PackgeFileCheckUtil.checkFileIsFull(AppContext.getInstance());
        if (!isFull) {
            LogUtils.e("默认资源文件不完整，请检查资源文件或者重写checkProfileIsFull方法");
            try {
                //重启应用，这样我们会重新进入登陆界面
                EnvironmentVariable.setPassword("");
                AppUtils.relaunchApp(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
        return true;
    }

    /**
     * 检查env是否含有用户信息
     *
     * @return
     */
    protected boolean checkUserValid() {
        if (EnvironmentVariable.getUserName() == null) {
            try {
//                Toast.makeText(context, "用户名失效，请重新登录", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent();
//                intent.setClass(this, Class.forName("com.efounder.activity.Login_withTitle"));
//                stopAllService();
//                startActivity(intent);
//                this.finish();

                LogoutEvent logoutEvent = new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE);
                LogOutUtil.notifyOffline(logoutEvent);
                return false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public void checkUpdateAndGnqx() {
        //检查用户、更新、及权限
        String username = EnvironmentVariable.getUserName();
        String password = EnvironmentVariable.getPassword();
        //开启线程加载是否升级，检查权限的功能
        String loginType = EnvironmentVariable.getProperty("LoginType");
        if (null != loginType && loginType.equals("0")) {
            //开始检查是否更新版本
            if (!getIntent().hasExtra("unDoCheck")) {
                LoginCheckManager loginCheckManager = new LoginCheckManager(this);
                loginCheckManager.checkVersionAfterLogin(LoginCheckManager.TYPE_NOT_LOGIN);
            }
        } else {
            //TODO 此处初始化EAI，具体位置，以后再考虑下。
            EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);
            EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
            EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
            EAI.Path = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
            EAI.Service = Constant.EAI_SERVICE;

            LoginUtil loginUtil = new LoginUtil();
            loginUtil.start(username, password,
                    new LoginUtilInterface() {
                        @Override
                        public void startProgress() {
                        }

                        @Override
                        public void loginSuccess(JResponseObject result) {
                            Map<?, ?> responseMap = result.getResponseMap();
                            JResponseObject pingtaiRO = (JResponseObject) responseMap.get("pingtai");
                            EFDataSet weChatDataSet = (EFDataSet) responseMap.get("extrawx");//获取返回的聊天id密码
                            Map<?, ?> pingtaiResponseMap = pingtaiRO.getResponseMap();

                            if (responseMap == null) {
                                ToastUtil.showToast(BaseMainHomeActivity.this, "登录失败，请联系管理员。");
                                return;
                            } else {
                                pingtaiRO = (JResponseObject) responseMap.get("pingtai");
                            }
                            if (pingtaiRO != null) {
                                pingtaiResponseMap = pingtaiRO.getResponseMap();
                                ///LoginManager.checkGNQXBYOSP(pingtaiResponseMap);//保存服务器返回的功能权限
                                String gnqxSetttingModel = EnvironmentVariable.getProperty("GNQXSET");
                                if (null != gnqxSetttingModel && gnqxSetttingModel.equals("0")) {
                                    //checkGNQXBYOSP(result);
                                    LoginManager.checkGNQXBYOSP(pingtaiResponseMap);
                                } else if (null != gnqxSetttingModel && gnqxSetttingModel.equals("2")) {
                                    LoginManager.checkGNQX(result);
                                }
                            } else {
                                ToastUtil.showToast(BaseMainHomeActivity.this, "登录失败，请联系管理员。");
                                return;
                            }
                            if (weChatDataSet != null) {
                                //存储微信聊天密码
                                List<EFRowSet> weChatEfRowSets = weChatDataSet.getRowSetArray();
                                EFRowSet weChatRowSet = weChatEfRowSets.get(0);
                                chatPassword = weChatRowSet.getString("F_IM_PASSWORD", "");
                                if (!("").equals(chatUserID) && !("").equals(chatPassword)) {
                                    String chatUserIDLocal = EnvironmentVariable.getProperty(CHAT_USER_ID);

                                    //处理后台更新他的消息ID的特殊情况
                                    if (chatUserID != chatUserIDLocal) {
                                        try {
//                                            Toast.makeText(context, "用户名失效，请重新登录", Toast.LENGTH_SHORT).show();
//                                            Intent intent = new Intent();
//                                            intent.setClass(BaseMainHomeActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
//                                            // stopAllService();
//                                            LogOutUtil.stopLocalIMService(BaseMainHomeActivity.this);
//                                            startActivity(intent);
//                                            BaseMainHomeActivity.this.finish();

                                            LogoutEvent logoutEvent = new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE);
                                            LogOutUtil.notifyOffline(logoutEvent);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        return;
                                    }
                                    EnvironmentVariable.setProperty(CHAT_USER_ID, chatUserID);
                                    EnvironmentVariable.setProperty(CHAT_PASSWORD, chatPassword);
                                }

                                String group_id = weChatRowSet.getString("group_id", "");
                                EnvironmentVariable.setProperty(chatUserID + "workgroup", group_id);

                                //处理聊天的权限
                                LoginManager.checkChatPermission(result);

                            }
                            //开始检查是否更新版本
                            if (!getIntent().hasExtra("unDoCheck")) {
                                apkUpdateManager.CheckAPKVerion(BaseMainHomeActivity.this, result, checkUpdateHandler);
                            }
                        }

                        @Override
                        public void loginFailed(String errorString) {
                            //密码错误   --- 密码失效
                            try {
                                Toast.makeText(context, errorString, Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent();
//////                                LogOutUtil.stopLocalIMService(BaseMainHomeActivity.this);
//////                                intent.setClass(BaseMainHomeActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
//////                                startActivity(intent);
//////                                finish();
                                LogoutEvent logoutEvent = new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE);
                                LogOutUtil.notifyOffline(logoutEvent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void exception(String exceptionString) {
                            LoadingDataUtilBlack.dismiss();
                            ToastUtil.showToast(BaseMainHomeActivity.this, exceptionString + "，请稍后重试。");
                        }
                    }
            );
        }
    }

    @Override
    public void refreshNotice() {
        if (willShowFragment instanceof PagerSlidingTabFragment) {
            if (((PagerSlidingTabFragment) willShowFragment).getAdapter().getCurrentFragment() instanceof MainFragment) {
                ((MainFragment) ((PagerSlidingTabFragment) willShowFragment).getAdapter().getCurrentFragment()).refreshGrid();
            }
        }
        if (willShowFragment instanceof PagerSlidingTab2Fragment) {
            if (((PagerSlidingTab2Fragment) willShowFragment).getAdapter().getCurrentFragment() instanceof MainFragment) {
                ((MainFragment) ((PagerSlidingTab2Fragment) willShowFragment).getAdapter().getCurrentFragment()).refreshGrid();
            }
        }
    }

    public interface TabBottomActivityResultListener {
        void onTabBottomActivityResult(int requestCode, int resultCode, Intent data);
    }


    public void setOnTabBottomActivityResultListener(
            TabBottomActivityResultListener onTabBottomActivityResultListener) {
        this.onTabBottomActivityResultListener = onTabBottomActivityResultListener;
    }

    //处理通过消息发送的app以及资源文件更新事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveUpdateEvent(UpdateResEvent event) {
        if (UpdateResEvent.TYPE_APP_UPDATE.equals(event.getType())) {
            String version = event.getVersion();
            String updateNote = event.getUpdateNote();
            String url = event.getUrl();
            LogUtils.i(TAG, "收到app更新的消息");
            if (apkUpdateManager.checkIsNeedToDown(version)) {//如果版本不一致
                boolean isForceUpdateApk = apkUpdateManager.checkIsNeedForceDown(version);//是否需要强制升级
                apkUpdateManager.downAPK(BaseMainHomeActivity.this, null, updateNote, url, apkUpdateManager, isForceUpdateApk, checkUpdateHandler);
            }

        } else if (UpdateResEvent.TYPE_APP_RES_UPDATE.equals(event.getType())) {
            String version = event.getVersion();
            String updateNote = event.getUpdateNote();
            LogUtils.i(TAG, "收到app资源更新的消息");
            final RESUpdateManager resUpdateManager = new RESUpdateManager();
            if (resUpdateManager.checkIsNeedToDown(version)) {//如果版本不一致
                apkUpdateManager.downAPPRes(BaseMainHomeActivity.this, updateNote, resUpdateManager, null, checkUpdateHandler);
            }
        }
    }

    //刷新view
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshViewEvent(RefreshViewEvent event) {
        if (event.getRefreshViewID() == RefreshViewEvent.VIEW_TABOTTOMACTIVITY) {
            // 皮肤存在，加载新皮肤
            File file = new File(SKIN_DIR, "mobile.skin");
            if (file != null && file.exists()) {
                SkinCompatManager.getInstance().loadSkin("mobile.skin", null, CustomSDCardLoader.SKIN_LOADER_STRATEGY_SDCARD);
            }
            //刷新界面
            refreshUi();
        }
    }

    //MenuFragment和OpenMenuFragment的刷新事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshNotice(RefreshMainNineGridViewEvent refreshMainNineGridViewEvent) {
        refreshNotice();
    }

    private static class MyHandler extends Handler {
        private final WeakReference<BaseMainHomeActivity> myClassWeakReference;

        public MyHandler(BaseMainHomeActivity myClassInstance) {
            myClassWeakReference = new WeakReference<>(myClassInstance);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseMainHomeActivity activity = myClassWeakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 0:
//                        activity.initView();
//                        break;
//                    case 1:
//                        //   refreshView();
//                        break;

                        //todo 不再使用此方式
//                    case 6://登陆后显示设定的tab页
//                        int defaultPosition = activity.tabbarView.getDefaultSelectedTab();
//                        if (defaultPosition != 0) {
//                            activity.showMenuByIndex(defaultPosition);
//                            activity.tabbarView.setCurrentTabColor(defaultPosition);
//                            TabBarNew.mCurrentTabIndex = defaultPosition;
//                        }
//                        break;
                    default:
                        break;
                }
                super.handleMessage(msg);
            }
        }
    }
}
